﻿//www.codeOften.com
//Senthil Maruthaiappan - senips (at) gmail.com
//see license on http://www.codeplex.com/Jinglebell


using System;
using System.ComponentModel;
using CodeOften.Container;
using JingleBell.Interface;

namespace JingleBell.Library
{
    [InstanceBehaviour(InstanceBehaviourType.Singleton)]
    public class ProcessRunner : IProcessRunner
    {
        private readonly IProcessListener _listner;

        [InstanceBehaviour(InstanceBehaviourType.AlwaysCreate)] private readonly ProcessQueue _processsQueue =
            new ProcessQueue();

        private readonly ISynchronizeInvoke _syncInvoke;
        private readonly bool stop;
        private IShellProcess _shellProcess;

        public ProcessRunner(IProcessListener listner, ISynchronizeInvoke syncInvoke)
        {
            _listner = listner;
            _syncInvoke = syncInvoke;
            stop = false;
        }

        public IServices Services { get; set; }

        #region IProcessRunner Members

        public IShellProcess ShellProcess
        {
            get { return _shellProcess; }
        }

        public IProcessQueue Queue
        {
            get { return _processsQueue; }
        }

        public void GoNext()
        {
            if (_processsQueue.Count == 0)
                return;
            if ((stop))
            {
                _processsQueue.Clear();
                return;
            }
            _shellProcess = Services.Get<ICommandShellProcess>(this);
            _shellProcess.Listener = _listner;
            _shellProcess.CreateProcess(_syncInvoke, _processsQueue.Dequeue);

            _shellProcess.CanGoNextProcess = false;
            try
            {
                _shellProcess.Start();
            }
            catch (Exception ee)
            {
                if (_listner != null)
                    _listner.ProcessFail(ee);
            }
        }

        public void Run()
        {
            GoNext();
        }

        #endregion
    }
}